<template>
  <div>
    <el-upload
      class="avatar-uploader"
      :action="src"
      list-type="picture-card"
      :show-file-list="false"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      :before-upload="beforeAvatarUpload"
    >
      <div v-if="imagesUrl" slot="tip" class="fileEdit">
        <span @click="handleRemove">
          <i class="el-icon-delete" />
        </span>
      </div>
      <img v-if="imagesUrl" :src="imagesUrl" class="avatar">

      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: String,
      default: function() {
        return ''
      }
    }
  },

  data() {
    return {
      imagesUrl: 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1483731740,4186543320&fm=26&gp=0.jpg',
      src: 'https://jsonplaceholder.typicode.com/posts/'
    }
  },
  watch: {
    value: {
      immediate: true,
      handler: function(value) {
        if (!value) {
          this.fileList = []
          this.imagesUrl = ''
          return
        }
        this.imagesUrl = value
        console.log(this.imagesUrl, 'dfd')
      }
    }
  },
  methods: {
    handleRemove(file) {
      this.fileList = []
      this.imagesUrl = ''
      this.$emit('input', this.imagesUrl)
    },
    // 上传成功
    handleSuccess(res, file) {
      this.imagesUrl = res.data.url
      // 图片路径返回给父组件
      this.$emit('input', this.imagesUrl)
    },
    // 上传成功之前 对图片格式要求
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG && !isJPG) {
        this.$message.error('上传图片只能是 JPG 格式和PNG格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return (isPNG && isLt2M) || (isJPG && isLt2M)
    }
  }
}
</script>

<style>
.fileEdit {
  position: absolute;
  right: 10px;
  top: 0;
}
.el-icon-download {
  cursor: pointer;
  color: red;
  font-size: 20px;
}
.el-icon-delete {
  cursor: pointer;
  color: red;
  font-size: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  /* width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center; */
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
